package com.example.cloudkit.common;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义排序相关工具类
 *
 * @author wangcl
 */
public class CollectionKit {

    /**
     * 将list中的元素根据指定的字段进行自定义排序,如果给定的集合没有匹配到自定义顺序中的数据，返回空集合
     *
     * @param list      要排序的list
     * @param field     要排序的字段
     * @param sortArray 自定义顺序
     * @return 排序后的list
     * @throws IllegalAccessException 字段访问权限异常
     */
    public static <T> List<T> sortByCustom(List<T> list, String field, Object[] sortArray)
            throws IllegalAccessException {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("list 不能为空");
        }
        if (field == null || field.isBlank()) {
            throw new IllegalArgumentException("field 不能为空");
        }
        if (sortArray == null || sortArray.length == 0) {
            throw new IllegalArgumentException("sortArray 不能为空");
        }
        List<T> newList = new ArrayList<>();
        for (Object sort : sortArray) {
            for (T t : list) {
                Field[] fields = t.getClass().getDeclaredFields();
                for (Field fieldItem : fields) {
                    fieldItem.setAccessible(true);
                    // 当前循环是指定的排序字段并且是排序值
                    if (fieldItem.getName().equals(field)) {
                        if (fieldItem.get(t).equals(sort)) {
                            newList.add(t);
                            break;
                        }
                    }
                }
            }
        }
        return newList;
    }

    /*public static void main(String[] args) throws IllegalAccessException {
        List<Demo> list = new ArrayList<>();
        Demo demo1 = new Demo();
        demo1.setId(1L);
        demo1.setName("小名");
        demo1.setAge(10);

        Demo demo2 = new Demo();
        demo2.setId(2L);
        demo2.setName("小里");
        demo2.setAge(34);

        Demo demo3 = new Demo();
        demo3.setId(3L);
        demo3.setName("小孔");
        demo3.setAge(52);
        list.add(demo1);
        list.add(demo2);
        list.add(demo3);
        Object[] idArray = new Long[]{1L, 2L, 3L}; // 123
        Object[] nameArray = new String[]{"小孔", "小名", "小里"}; // 312
        Object[] ageArray = new Integer[]{52, 34, 10}; // 321
        List<Demo> idList = sortByCustom(list, "id", idArray);
        List<Demo> nameList = sortByCustom(list, "name", nameArray);
        List<Demo> ageList = sortByCustom(list, "age", ageArray);
        System.out.println(idList);
        System.out.println(nameList);
        System.out.println(ageList);
    }

    @Data
    static class Demo {
        private Long id;
        private String name;
        private Integer age;
    }*/
}
